<template>
	<view  v-show="!loginShow" >
	<view  class="first" style="height:60vh; width:100%; border: 0px solid red;  display: flex;justify-content: center;align-items: center;" >
	<view  class="first" style=" display: block; width:100%; border: 0px solid red;" >
		<view  class="first" style="width:100%; border: 0px solid red; height:100px;" >
		<b>读心AI</b>
		</view>
		
		<view  class="first" style="width:100%; border: 0px solid red;" >
		<TnLoading show animation  color="#01beff" type="success" mode="flower"
		duration="1" time-function="ease-in-out" size="100px" />
		</view>
	</view>
	</view>
	</view>
	
	<view  v-show="loginShow" >
	<view  v-show="false" style="border: 0px solid red; width:100%; height:100vh; display: flex;justify-content: center; align-items: center; " >
	
	<view  style="border: 0px solid blue; width:100%; height:350px;  " >
	
	<view  style="border: 0px solid red; width:100%; height:30%;  display: flex;justify-content: center; align-items: center;" >
	 <image style="width:100px; height:100px;" :src="avatarUrl" ></image>
	</view>
	<view  style="border: 0px solid red; width:100%; height:10%;  display: flex;justify-content: center; align-items: flex-start;" >
	 <TnButton height="30px"  width="100px" open-type="chooseAvatar" @chooseavatar="tChooseAvatar"  >获取登录头像</TnButton>
	</view>
	

	<view  style="border: 0px solid red; width:100%; height:20%;  display: flex;justify-content: center; align-items: center;" >
	<input type="nickname" id="tnickname"  @blur="handleInput"
	v-model="nickname"  placeholder="请点击获取或输入昵称"/>
	</view>
	

	
	<view  style="border: 0px solid red; width:100%; height:20%;  display: flex;justify-content: center; align-items: center;" >
	<TnButton height="30px"  width="200px" open-type="getPhoneNumber" 
	  @getphonenumber="gettPhoneNumber"  > 登录 </TnButton>
	</view>
	

	</view>
	
	
	</view>
	</view>
	
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app';
import TnButton  from '@/uni_modules/tuniaoui-vue3/components/button/src/button.vue'
import TnLoading from '@/uni_modules/tuniaoui-vue3/components/loading/src/loading.vue'
import { weixinlogin, userlogin, weixinUserLogin } from '@/api/login'
import { setTokenRefCode } from '@/utils/auth'
import { ref, reactive, getCurrentInstance  } from 'vue'

const avatarUrl = ref('https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0')
const nickname  = ref('')
const refcode   = ref("")
const loginShow = ref(false)

onLoad((options) => {
console.log( "===========login=============start" )
console.log('1 页面 refcode : ', options.refcode );	
	uni.login({
		"provider": "weixin",
		success: function(res){
			// 获取用户信息
			uni.getUserInfo({
				provider: 'weixin',
				success: function (infoRes) {
					console.log('用户昵称为：' + infoRes.userInfo.nickName);
					console.log( infoRes )
					const deviceId = uni.getSystemInfoSync().deviceId;
					const data = { signature: infoRes.signature,
								encryptedData: infoRes.encryptedData,
								iv: infoRes.iv,
								code: res.code,
								deviceid: deviceId,
								refcode:  options.refcode,
					}
					userlogin( data, loginShow )
				}
			})
		}
	})
})

//获取用户头像
const tChooseAvatar = (e) => {
	console.log("=================tChooseAvatar=================");
	console.log(e)
	let base64String = ""
	let index = e.detail.avatarUrl.indexOf("wxfile://");
	console.log("index=====================: " + index)
	if(index>=0){
		base64String = wx.getFileSystemManager().readFileSync(e.detail.avatarUrl, 'base64');
		avatarUrl.value = `data:image/jpeg;base64,${base64String}`;
		return
	}

	uni.request({
	          url: e.detail.avatarUrl,
	          responseType: 'arraybuffer' // 设置响应类型为 ArrayBuffer
	}).then(res => {
				console.log("===============request===================");
				console.log( res )
				if (res.statusCode === 200) {
				          const arrayBuffer = res.data;
				          base64String = wx.arrayBufferToBase64(arrayBuffer);
				          avatarUrl.value = `data:image/jpeg;base64,${base64String}`;
				          console.log('图片已下载为Base64:', avatarUrl.value );
				} else {
				          console.error('请求失败，状态码:', res.statusCode);
				}
	})
}

const handleInput = () => {
	console.log("==============funcnickname===================");
	console.log(nickname.value)
	uni.createSelectorQuery()
	.select("#tnickname").fields({
	        properties: ["value"],
	}).exec((res) => {  
	        const nickName = res?.[0]?.value  
			console.log('获取昵称', nickName)
			nickname.value = nickName
	})
}

const gettPhoneNumber = (e) => {
	console.log("===============gettPhoneNumber===================");
	console.log(e);
	uni.login({
		"provider": "weixin",
		"onlyAuthorize": true, // 微信登录仅请求授权认证
		success: function(res){
			console.log(res );
			const data = { 
				        headerImage: avatarUrl.value,
						nickName: nickname.value,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
						code: res.code,
						deviceid: uni.getSystemInfoSync().deviceId,
						refcode:  refcode.value,
			}
			weixinUserLogin( data ).then(res => {
				console.log( res )
				if( res.data.token !=null ){
					setTokenRefCode(res.data)
					uni.redirectTo({
						url:'/pages/index/index'
					});
				}

			}).catch(error => {
				console.log("=========gettPhoneNumber=========================");
				console.log( error )
				uni.showToast({
				icon: 'fail',
				title: "登录失败",
				duration: 3000 // 持续时间为3000毫秒，即3秒
				})
			})
		}
	});
}




</script>

<style>

.first{
	border: 1px solid red;
	height: 100px; 		/* 使用100%的高度来覆盖整个屏幕 */
	width:100%;
	/* 使用100%的高度来覆盖整个屏幕 */
	display: flex;
	justify-content: center;
	align-items: center;
}


</style>
